package com.lyrcsoft.controller;

import com.lyrcsoft.entities.User;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author fujc-dev@qq.com
 * @date 2023/7/12 15:09
 */
@RestController
@RequestMapping("/user1")
public class UserController {

    @PostMapping("/add")
    public void add(@Valid User user, BindingResult result) {
        Optional<List<String>> op = valid(result);
        op.ifPresent(strings -> strings.forEach(System.out::println));
    }

    protected Optional<List<String>> valid(BindingResult result) {
        if (result.hasErrors()) {
            List<String> list = result.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
            return Optional.of(list);
        }
        return Optional.empty();
    }

}

